package com.DHH.Controller.Api;

import com.DHH.Config.ApiConstant;
import com.DHH.Config.Constant;
import com.DHH.Dto.ApiMessage;
import com.DHH.Dto.Message;
import com.DHH.Entity.Base.BaseLoginRecord;
import com.DHH.Entity.Base.BaseThirdpartyLogin;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Base.BaseUserInfo;
import com.DHH.Mapper.Api.ApiBaseUserMapper;
import com.DHH.Mapper.Base.BaseThirdpartyLoginMapper;
import com.DHH.Mapper.Base.BaseUserInfoMapper;
import com.DHH.Service.Base.IBaseLoginRecordService;
import com.DHH.Service.Base.IBaseUserService;
import com.DHH.Util.Http;
import com.DHH.Util.MyUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汪玉东 on 2017/8/4.
 */
@Controller
@RequestMapping("/api//")
public class ApiLoginController {


    @Autowired
    private IBaseLoginRecordService baseLoginRecordService;

    @Resource
    private IBaseUserService baseUserService;
    @Resource
    private ApiBaseUserMapper apiBaseUserMapper;
    @Resource
    private BaseUserInfoMapper baseUserInfoMapper;
    @Resource
    private BaseThirdpartyLoginMapper baseThirdpartyLoginMapper;




    @RequestMapping("login")
    @ResponseBody
    public ApiMessage login(String openId, HttpServletRequest request, HttpServletResponse response){
        BaseUser user= apiBaseUserMapper.getUserInfoByOpenId(openId);
        if(user==null){
            user=new BaseUser();
            user.setToken(openId);
            user.setIdentity("wx"+System.currentTimeMillis());
            user.setUsername("微信");
            user.setUserSource("微信小程序");
            user=baseUserService .insertBaseUser(user);
            BaseThirdpartyLogin baseThirdpartyLogin=new BaseThirdpartyLogin();
            baseThirdpartyLogin.setUserId(user.getId());
            baseThirdpartyLogin.setOpenId(openId);
            baseThirdpartyLogin.setLoginTypeId(1);
            baseThirdpartyLoginMapper.insert(baseThirdpartyLogin);
        }
        user.setToken(openId);
        ApiMessage apiMessage=wxLogin(user,0,request,response);
        if(apiMessage.isState()){
            user.setToken("");
            BaseUserInfo baseUserInfo=new BaseUserInfo();
            baseUserInfo.setUserId(user.getId());
            System.out.println(baseUserInfo);
            baseUserInfo=baseUserInfoMapper.selectOne(baseUserInfo);
            apiMessage.setUser(user);
            apiMessage.setUserInfo(baseUserInfo);
        }
        return apiMessage;
    }



    @RequestMapping("getOpenId")
    @ResponseBody
    public Message getOpenId(String code,HttpServletRequest request, HttpServletResponse response){
        JSONObject jsonObject=null;
       try{
           Map<String,Object> parms=new HashMap<String, Object>();
           parms.put("appid", ApiConstant.APIID);
           parms.put("secret",ApiConstant.SECRET);
           parms.put("js_code",code);
           parms.put("grant_type",ApiConstant.GRANTTYPE);
           Http http=new Http();
           String rs= http.sendGet(ApiConstant.WX_OPENIDURL,parms,"utf-8");
           jsonObject=JSON.parseObject(rs);
           String sessionKey=jsonObject.get("session_key").toString();
           String openId=jsonObject.get("openid").toString();
           return  login(openId,request,response);
       }catch (Exception e){
           e.printStackTrace();
           ApiMessage apiMessage=new ApiMessage();
           apiMessage.setData(jsonObject);
           apiMessage.setState(false);
           return  apiMessage;
       }

    }


    public ApiMessage wxLogin (BaseUser user, Integer autoLogin, HttpServletRequest request, HttpServletResponse response){
        BaseLoginRecord baseLoginRecord=new BaseLoginRecord();
        baseLoginRecord.setLoginName(user.getIdentity());
        baseLoginRecord.setLoginIp(MyUtil.getRemoteHost(request));
        baseLoginRecord.setLoginTime(new Date());
        baseLoginRecord.setIsSuccess(0);
        ApiMessage msg=new ApiMessage();
        org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
        Session session=currentUser.getSession();
        String  sessionIdentifyCode = (String) session.getAttribute(Constant.IDENTIFY_CODE_MARK);
        session.setAttribute(Constant.IDENTIFY_CODE_MARK,null);
        if(user.getIdentity()==null||user.getIdentity().equals(""))
        {
            msg.setMsg("请输入正确的用户名!");
            return msg;
        }if(user.getToken()==null||user.getToken().equals(""))
        {
            msg.setMsg("请输入正确的密码!");
            return msg;
        }
        Integer number= (Integer) session.getAttribute(Constant.LOGIN_FAILED_NUMBER_MARK);
        number=(number==null?0:number);
        if(number>= Constant.LOGINFAILEDNUMBER)
        {
            msg.setMsg("您重复登录次数过多，请30分钟后重试！");
            baseLoginRecord.setLoginMessage("登录次数过多..");
            baseLoginRecordService.insertBaseLoginRecord(baseLoginRecord);
            return msg;
        }
        try{
            BaseUser u=new BaseUser();
            u.setIdentity(user.getIdentity());
            u.setIslock(0);
            u= apiBaseUserMapper.selectOne(u);
            String password= MyUtil.createMD5(user.getToken());
            password=MyUtil.createMD5(password+u.getSalt());
            UsernamePasswordToken token=new UsernamePasswordToken(user.getIdentity(),password);

            currentUser.login(token);
            if(autoLogin!=null && autoLogin==1)
            {     token.setRememberMe(true);
            }
            currentUser.login(token);
            u= apiBaseUserMapper.getUserInfoByIdRelation(u.getId());
            session.setAttribute(Constant.USER_IDENTIFICATION,u);
            msg.setState(true);
            msg.setMsg("恭喜你登录成功");
            baseLoginRecord.setLoginMessage("(微信)登录成功..");
            baseLoginRecord.setTypeId(2);
            baseLoginRecord.setUserId(user.getId());
            baseLoginRecordService.insertBaseLoginRecord(baseLoginRecord);
            return  msg;

        }catch (Exception e)
        {  e.printStackTrace();
            Integer loginfailedNumber= (Integer) session.getAttribute(Constant.LOGIN_FAILED_NUMBER_MARK);
            if(loginfailedNumber==null)
            {
                loginfailedNumber=0;
            }
            msg.setMsg("登录失败，请检查账号或密码错误！");
            baseLoginRecord.setLoginMessage("(微信)登录失败.");
            baseLoginRecordService.insertBaseLoginRecord(baseLoginRecord);
            session.setAttribute(Constant.LOGIN_FAILED_NUMBER_MARK,loginfailedNumber+1);
            return msg;
        }

    }
}
